// Gets an XMLHttp object /ActiveX object
function getHTTPObject() { 
	var result;
	try {
		result = new ActiveXObject('Msxml2.XMLHTTP');
	} catch (e) {
		try {
			result = new ActiveXObject('Microsoft.XMLHTTP');
		} catch (e2) {
			try {
				result = new XMLHttpRequest();
			} catch (e3) {
				result = false;
			}
		}
	}
	return result;
}

//Handles asynchronous GET requests
function doAjaxRequest(page, area) {
	if(counter !=null) clearTimeout(counter); //We don't need to keep counting if a new page is going to be loaded (see countdown.js)
	var xmlHttp = getHTTPObject();

	if (area != null) {
		xmlHttp.open('GET', page, true);
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					fillContent(xmlHttp.responseText, area);
				}
			}
		};
		xmlHttp.send(null);
	}
}

//Handles asynchronous POST requests
//enctype parameter can be:
//application/x-www-form-urlencoded
//multipart/form-data
//text/plain
function doAjaxPostRequest(page, area, postParameters, enctype){
	if(counter !=null) clearTimeout(counter); //We don't need to keep counting if a new page is going to be loaded (see countdown.js)
	var xmlHttp = getHTTPObject();

	if (area != null) {
		
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					fillContent(xmlHttp.responseText, area);
				}
			}
		};
		xmlHttp.open('POST', page, true);
		xmlHttp.setRequestHeader("Content-type", enctype);
		xmlHttp.send(postParameters);
	}
}

//After every succesful asynchronous request, this function will be called to display the retrieved data
function fillContent(text, area) {
	var div = document.getElementById(area);

	if (text != "") {
		div.innerHTML = text;
	}
	//The following try-catch blocks are events that should occur after filling in the retrieved content
	//Said events can be:
	//-Hiding/showing the menu
	//-loading a default search after loading the searchbar page
	//-starting 1 countdown for 1 or more auction items
	//all errors generated do not have to be dealt with, as an error will occur only when the event does not have to be called
	try {
		var showmenu = document.getElementById('showmenu').value;
		if(showmenu == 'true') setElementVisibility("menu", "block");
		else if(showmenu == 'false') setElementVisibility("menu", "none");
	} catch(error) {}//Errors when no change in menu visiblity is specified
	try {
		var loadDefault = document.getElementById('loadDefault').value;
		document.getElementById('loadDefault').value = false;// other wise endless repeats! do not want!
		if(loadDefault == 'my-auctions'){ doAuctionSearch("my-auctions");}
		else if(loadDefault == 'my-bids'){ doAuctionSearch("my-bids");}
	} catch(error) {}// Errors when no results should be shown by default on the searchbar page
	try {
		var countDown = document.getElementById('countdown');
		if(countDown != null) {
			var timerEls = getElementsByClass("item-to-time"); //Get all the items that need to be timed
			timerElements = new Array();//timerElements variable is in the countdown.js
			timeLeft = new Array();		//as is the timeleft variable
			for (var i=0;i<timerEls.length;i++) { //Set the variables for countdown usage later, see countdown function in countdown.js
				var arrayPos = timerElements.length;
				timerElements[arrayPos] = timerEls[i].parentNode;
				timeLeft[arrayPos] = Math.floor(timerEls[i].value);
			}
			if(counter !=null) clearTimeout(counter); 	//Counter variable is in the countdown.js
			countdown(countDown.value);					//as is the countdown function
		}
	} catch(error) {}//Errors when no countdown is nescesary
}

//Generic "load this page" function
function doLoad(page, area) {
	doAjaxRequest("getPage.do?getContent=" + page, area);
}

//For loading any page that isn't account related
function doLoadAndHideAccountMenu(page, area) {
	setElementVisibility("accountmenu", "none");
	doLoad(page,area);
}

//For loading the account menu page, only the menu has to be shown (as of yet)
function doLoadAccount(){
	setElementVisibility("accountmenu", "block");
	clearArea('content');
	if(counter !=null) clearTimeout(counter); //We don't need to keep counting if a new page is going to be loaded (see countdown.js)
}

//To perform a search on the Auctions, My-auctions or My-bids pages
function doAuctionSearch(searchTarget) {
	var search = document.getElementById("searchfield").value;
	if (search.length > 0 || searchTarget == 'my-auctions' || searchTarget == 'my-bids') {
		doAjaxRequest("AuctionItemServlet.do?action=search&searchTerm=" + search
				+ "&searchTarget=" + searchTarget, "subcontent");
	} else {
		if(counter !=null) clearTimeout(counter); //We don't need to keep counting if a new page is going to be loaded (see countdown.js)
		clearArea("subcontent");	
	}
}

//Going to the detailed page of an auction item
function doGoToAuction(auctionItemID){
	doAjaxRequest("AuctionItemServlet.do?action=GoToAuction&auctionItemID=" + auctionItemID, "content");
}

//Logging in
function doLogin() {
	var name = document.getElementById('name').value;
	var pass = document.getElementById('password').value;
	var postParameter = "name=" + name + "&password=" + pass;
	doAjaxPostRequest("AccountServlet.do?action=login", "content", postParameter, "application/x-www-form-urlencoded");
}

//Registering an account
function doRegisterAccount() {
	var name = document.getElementById('name').value;
	var pass = document.getElementById('password').value;
	var passrep = document.getElementById('passwordrepeat').value;
	var postParameter = "name=" + name + "&password=" + pass + "&passwordrepeat=" + passrep;
	doAjaxPostRequest("AccountServlet.do?action=register", "content", postParameter, "application/x-www-form-urlencoded");
}

//Deleting an auction item
function doDeleteAuctionItem(auctionItemID){
	var postParameter = "AID=" + auctionItemID 
						+ "&searchTerm=" + document.getElementById("searchfield").value 
						+ "&searchTarget=my-auctions";
	doAjaxPostRequest("AuctionItemServlet.do?action=delete", "subcontent", postParameter, "application/x-www-form-urlencoded");
}

//Creating an auction item
function doCreateAuction(){
	var postParameter = "titleName=" + document.getElementById("name").value +
						"&startPrice=" + document.getElementById("price").value + 
						"&description=" + document.getElementById("description").value;
	doAjaxPostRequest("AuctionItemServlet.do?action=newAuction", "content", postParameter, "application/x-www-form-urlencoded");
}

//Updating account info (changing password only atm)
function doUpdateAcountInfo(){
	var postParameter = "password=" + document.getElementById("password").value +
						"&newPasswordRepeat=" + document.getElementById("newpasswordrepeat").value +
						"&newPassword=" + document.getElementById("newpassword").value;
	doAjaxPostRequest("AccountServlet.do?action=update", "content", postParameter, "application/x-www-form-urlencoded");
}

//Bidding on an auction item
function doBid(auctionItemID){
	var postParameter = "bidValue=" + document.getElementById("bid").value +
						"&auctionItemID=" + auctionItemID;
	doAjaxPostRequest("AuctionItemServlet.do?action=bid", "content", postParameter, "application/x-www-form-urlencoded");
}

//Going to the edit page of an auction item
function doGoToEdit(auctionItemID){
	doAjaxRequest("AuctionItemServlet.do?action=doGoToEdit&auctionItemID=" + auctionItemID, 'content');
}

//Performing the edit on an auction item
function doEdit(auctionItemID){
	var postParameter = "titleName=" + document.getElementById("name").value +
						"&auctionItemID=" + auctionItemID + 
						"&description=" + document.getElementById("description").value;
	doAjaxPostRequest("AuctionItemServlet.do?action=doEdit", "content", postParameter, "application/x-www-form-urlencoded");
}

//Clearing the contents of an element based on the ID of of the element
function clearArea(area) {
	var div = document.getElementById(area);
	div.innerHTML = "";
}

//Hiding or showing an element (noneOrBlock should be "none" or "block")
function setElementVisibility(target, noneOrBlock) {
	document.getElementById(target).style.display = noneOrBlock;
}

//Retrieves all the elements with the class name specified (string)
//from the given domNode if specified (element, default = entire page)
//but only those with the given tagName if specified (string, default = every tag)
//Credits: Dustin Diaz
//Source: http://www.dustindiaz.com/getelementsbyclass
function getElementsByClass( searchClass, domNode, tagName) { 
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(var i=0,j=0; i<tags.length; i++) { 
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1) { 
			el[j] = tags[i];
			j++;
		}
	} 
	return el;
}